Ext.Loader.setPath('FormFieldUtil',contextPath+"ui_tpl/FormFieldUtil.js");
Ext.define('Ext.ux.GridFieldSet',{
		extend:'Ext.container.Container',
		xtype:'grid_fieldset',
		layout:'border',
		requires:[
			'Ext.toolbar.Paging',
			'FormFieldUtil'
		],
		initComponent:function(){
			var me=this,metaData=me["metaData"],
			mainMetaId=this.mainMetaId,
			globalId=this.globalId,
			refMetaMap=this.refMetaMap=metaData["refMetaMap"],
			refEnumMap=this.refEnumMap=metaData["refEnumMap"],
			gridCmpId=me["gridCmpId"]="grid_"+mainMetaId+"_"+globalId,
			attrCmpId=me["attrCmpId"]="attrPanel_"+mainMetaId+"_"+globalId,
			mainMeta=this.mainMeta=refMetaMap[mainMetaId],
			attrs=this.attrs=mainMeta["attrs"],
			action=attrs["action"],
			moduleProperty=this.moduleProperty=attrs['moduleProperty'],
			parentIdProperty=this.parentIdProperty=attrs['parentIdProperty'],
			items=me.items=[];
			if(!action){
				action={url:(contextPath+"meta/record/"+mainMetaId),type:"rest"};
			}
			var create=this.create=attrs["create"],
			update=this.update=attrs["update"],
			destroy=this.destroy=attrs["destroy"],
			query=this.query=attrs["query"];
			if(create){
				create["url"]=create["url"]||action["url"];
			}else{
				create={};
				this.create=create;
				Ext.apply(create,action);
				create["method"]="PUT";
			}
			if(update){
				update["url"]=update["url"]||action["url"];
			}else{
				update={};
				this.update=update;
				Ext.apply(update,action);
				update["method"]="POST";
			}
			if(destroy){
				destroy["url"]=destroy["url"]||action["url"];
			}else{
				destroy={};
				this.destroy=destroy;
				Ext.apply(destroy,action);
				destroy["method"]="DELETE";
			}
			if(query){
				query["url"]=query["url"]||action["url"];
				query["method"]=query["method"]||"GET";
			}else{
				query={};
				this.query=query;
				Ext.apply(query,action);
				query["method"]="PUT";
			}
			me.metaData=metaData;
			Ext.applyIf(this,attrs);
			this.initColumns();
			this.initDataGrid('center'),
			this.initFieldSet('east');
			this.items=[];
			this.items.push(this.gridConfig);
			this.items.push(this.attrProps);
			this.callParent();
		},
		
		initColumns:function(){
			var me=this,mainMeta=me["mainMeta"],refEnumMap=me["refEnumMap"],
			fields=mainMeta["fields"],typeMap=me["typeMap"],
			modelFields=this.modelFields=[],
			columns=this.columns=[],colMap=this.gridHeaderMap={},
			moduleProperty=me["moduleProperty"];
			Ext.iterate(fields,function(field,i){
				var type=field["type"],name=field["name"],
				attrs=field["attrs"],enums=attrs["enums"],
				f={name:name,type:typeMap[field["type"]]},
				col={dataIndex:name,text:field["text"],menuDisabled:true},
				valid={};
				colMap[f["name"]]=col;
				if(enums&&refEnumMap[enums]){
					col["renderer"]=function(){
						var vf=attrs["valueField"]||"code",
						df=attrs["displayField"]||"text",
						enumData=refEnumMap[enums]["list"],
						remap={};
						Ext.iterate(enumData,function(n,i){
							remap[n[vf]+""]=n[df];
						});
						return function(v){
							return remap[v+""];
						}
					}();
				}
				switch(type){
				case -5:
				case 4:
					break;
				case 91:
					col["renderer"]=Ext.util.Format.dateRenderer('Y-m-d');
					break;
				case 92:
					col["renderer"]=Ext.util.Format.dateRenderer('h:i:s');
					break;
				case 93:
					col["renderer"]=Ext.util.Format.dateRenderer('Y-m-d h:i:s');
					col["width"]=150;
					break;
				}
				modelFields.push(f);
				columns.push(col);
			});
			if(moduleProperty){
				var mp=colMap[moduleProperty];
				if(mp){
					mp["hidden"]=true;
				}
			}
			if(me.parentIdProperty&&me.globalId){
				var mp=colMap[me.parentIdProperty];
				if(mp){
					mp["hidden"]=true;
				}
			}
		},
		initGridModel:function(){
			var proxy=this.initGridProxy(),modelFields=this.modelFields,attrs=this.attrs,
			modelName=this.modelName=this.modelName||("Ext.model."+this["mainMeta"]["code"]+"_"+this["globalId"]);
			if(!Ext.ClassManager.isCreated(modelName)){
				Ext.define(modelName,{
					extend:"Ext.data.Model",
					idProperty:attrs["idProperty"]||"id",
					fields:modelFields,
					proxy:proxy
				});
			}
			
		},
		initGridStore:function(){
			this.initGridModel();
			var me=this,sortParam='sortInfo.field',store=this.store=Ext.create('Ext.data.Store',{
				model:me["modelName"],
				autoLoad:true,
				sorters:[{
					property:attrs["seqProperty"]||"seq",
					direction:"ASC"
				}]
			});
			var mainProperty=me["parentIdProperty"],seqProperty=me["seqProperty"],mainMetaId=me["mainMetaId"];
			if(mainProperty&&me.globalId){
				var proxy = me.store.getProxy(),
			       extraParams= proxy.extraParams;
				extraParams["filter."+me.parentIdProperty]=me.globalId;
				if(seqProperty){
					extraParams[sortParam]=seqProperty;
				}
			}
			
			return store;
		},
		initTbar:function(){
			var me=this,tbar=this.tbar=[{
				text:"新增",
				iconCls:"fa fa-plus",
				handler:function(){
					me.showAddNodeWin();
				}
			},{
				text:"编辑",
				iconCls:"fa fa-edit",
				handler:function(){
					me.showEditNodeWin();
				}
			},{
				text:"删除",
				iconCls:"fa fa-remove",
				handler:function(){
					me.doDelete();
				}
			},{
				text:"刷新",
				iconCls:'fa fa-refresh',
				handler:function(){
					me.refreshGrid();
				}
			}];
			if(me["seqProperty"]){
				this.moveUrl=contextPath+"meta/record/offset/"+me.mainMetaId;
				tbar.push({
					text:"上移",
					iconCls:"fa fa-arrow-up",
					handler:function(){
						var sels=me.getComponent(me.gridCmpId).getSelection();
						if(sels.length==0)return;
						var sel=sels[0];
						Ext.Ajax.request({
							url:me.moveUrl,
							params:{
								id:sel.get(me.idProperty),
								step:-1
							},
							success:function(){
								me.refreshGrid();
							},
							failure:function(){
								me.refreshGrid();
							}
						});
						
					}
				});
				tbar.push({
					text:"下移",
					iconCls:"fa fa-arrow-down",
					handler:function(){
						var sels=me.getComponent(me.gridCmpId).getSelection();
						if(sels.length==0)return;
						var sel=sels[0];
						Ext.Ajax.request({
							url:me.moveUrl,
							params:{
								id:sel.get(me.idProperty),
								step:1
							},
							success:function(){
								me.refreshGrid();
							},
							failure:function(){
								me.refreshGrid();
							}
						});
					}
				});
			}
			return tbar;
		},
		
		showAddNodeWin:function(){
			var me=this,mainMeta=this.mainMeta,
			moduleId=this.mainMetaId,attrs=mainMeta["attrs"],
			idProperty=attrs["idProperty"]||"id",
			typeProperty=attrs["typeProperty"]||"meta",
			create=me["create"],
			winName=this.addNodeWinName="addNodeWin_"+moduleId+"_"+me["globalId"];
			var win=Ext.getCmp(winName);
			if(!win){
				var items=FormFieldUtil.getFormFields(moduleId,metaData);
				Ext.iterate(items,function(item,i){
					var name=item["name"];
					if(name=="rank"){
						item.value=(moduleId);
						item.hidden=true;
					}else if(name==idProperty){
						item.value=-1;
						item.hidden=true;
					}else if(name=="seq"){
						item.hidden=true;
					}else if(name=="flag"){
						item.value=1;
					}else if(name==me["parentIdProperty"]){
						item.readOnly=true;
					}
				});
				win=new Ext.form.Panel({
					floating:true,
					title:"新增",
					id:winName,
					bodyPadding:10,
					url:create["url"],
					closeToolText:"关闭",
					draggable:true,
					modal:true,
					closable:true,
					scrollable:true,
					width:400,
					maxHeight:450,
					defaults:{
						xtype:"textfield",
						width:300
					},
					method:create["method"]||"PUT",
					items:items,
					buttons:[{
						text:'提交',
						formBind:true,
						handler:function(){
							 var win=this.up('form'),form = win.getForm();
					            if (form.isValid()) {
					                form.submit({
					                    success: function(form, action) {
					                    	Ext.toast("新增成功",'提示', 't');
					                    	me.refreshGrid();
					                    	win.hide();
					                    	
					                    },
					                    failure: function(form, action) {
					                    	Ext.toast(action.result.msg,'提示', 't');
					                    	me.refreshGrid();
					                    }
					                });
					            }	
						}
					},{
						text:'取消',
						handler:function(){
							this.up('form').hide();
						}
					}]
				});
			}
			var form=win.getForm(),pfield=form.findField(me.parentIdProperty);
			pfield&&pfield.setValue(me.globalId);
			Ext.iterate(this.defaultValueMap,function(name,v){
				var f=form.findField(name);
				f&&f.setValue(v);
			});
			win.show();
			
		},
		doDelete:function(){
			var me=this,sels=me.getComponent(me['gridCmpId']).getSelection();
			if(sels.length==0)return Ext.toast("请先选择要删除的记录",'提示');
			Ext.Msg.confirm('警告','确认删除',function(btn){
				if(btn=="no")return;
				Ext.iterate(sels,function(sel,i){
					sel.erase({
			            callback: function(record, operation, success) {
			                me.refreshGrid();
			            }
			        });
				});
			});
			
		},
		showEditNodeWin:function(){
			var me=this,moduleId=me["mainMetaId"];
			var sels=me.getComponent(me["gridCmpId"]).getSelection();
			if(sels.length==0)return Ext.toast('请先选择记录');
			var winName=this.editNodeWinName=this.editNodeWinName||("editNodeWin_"+moduleId+"_"+me["globalId"]),
			update=me["update"];
			var win=Ext.getCmp(winName);
			if(!win){
				items=FormFieldUtil.getFormFields(moduleId,metaData),
				idProperty=me["idProperty"],
				typeProperty=me["typeProperty"];
				Ext.iterate(items,function(item,i){
					var name=item["name"];
					if(name=="rank"){
						item.value=moduleId;
						item.hidden=true;
					}else if(name=="flag"){
						item.value=1;
					}
				});
				win=new Ext.form.Panel({
					floating:true,
					title:"编辑",
					bodyPadding:10,
					itemId:winName,
					url:update["url"],
					closeToolText:"关闭",
					draggable:true,
					closable:true,
					modal:true,
					scrollable:true,
					width:400,
					maxHeight:450,
					defaults:{
						xtype:"textfield",
						width:300
					},
					method:update["method"],
					items:items,
					buttons:[{
						text:'提交',
						formBind:true,
						handler:function(){
							 var win=this.up('form'),form = win.getForm();
					            if (form.isValid()) {
					                form.submit({
					                    success: function(form, action) {
					                    	Ext.toast("更新成功",'提示', 't');
					                    	me.refreshGrid();
					                    	win.hide();
					                    	
					                    },
					                    failure: function(form, action) {
					                    	Ext.toast(action.result.msg,'提示', 't');
					                    	me.refreshGrid();
					                    }
					                });
					            }	
						}
					},{
						text:'取消',
						handler:function(){
							this.up('form').hide();
						}
					}]
				});
			}
			var rec=sels[0],data=rec.data;
			if(this.needKeyConvert&&!data.flatten){
				data["flatten"]=true;
				Ext.apply(data,Ext.Object.flatten(data));
			}
			win.getForm().loadRecord(rec);
			win.show();
		},
		refreshGrid:function(){
			this.store.reload();
		},
		initGridProxy:function(){
			var me=this,query=me["query"],mainMeta=this.mainMeta,
			attrs=mainMeta['attrs'],
			startParam ="pageInfo.start",limitParam="pageInfo.limit",pageParam="pageInfo.page",
			sortParam="sortInfo.field",directionParam="sortInfo.direct",
			paramNames={
					startParam:startParam,
					limitParam:limitParam,
					pageParam:pageParam,
					sortParam:sortParam,
					directionParam:directionParam
					},
					extraParams={};
			extraParams[startParam]= 0;
			extraParams[limitParam]=25;
			extraParams[sortParam]=(attrs.idProperty||"id");
			extraParams[directionParam]="ASC";
			var proxy= {
					url:query["url"],
					type:query["type"],
					extraParams: extraParams,
					reader: {  
		                type: 'json',
		                rootProperty: 'itemList',
		                totalProperty: 'pageInfo.total'
		            },
		            simpleSortMode: true
				};
			Ext.apply(proxy,paramNames);
			return proxy;
		},
		initDataGrid:function(region){
			this.initGridStore();
			this.initTbar();
			
			var me=this,config=this.gridConfig={
				region:region,
				xtype:'grid',
				tbar:me.tbar,
				itemId:me["gridCmpId"],
				store:me.store,
				columns:me.columns,
				height:300,
				split:true,
				height:'auto',
				viewConfig: {
			        trackOver: false,
			        stripeRows: false,
			        enableTextSelection:true
			    },
				bbar: {
			        xtype: 'pagingtoolbar',
			        displayInfo: true,
			        displayMsg: ' {0} - {1} 总： {2}',
			        emptyMsg: "无数据",
			        store:me.store
			    },
				width:'auto',
				listeners:{
					'itemclick':function( view, record, item, index, e, eOpts ) {
						var fieldId=record.get(me["idProperty"]),
						attrPanel=me.getComponent(me["attrCmpId"]);
						attrPanel.loadData(fieldId);
					},
					'itemdblclick':function( view, record, item, index, e, eOpts ) {
						var fieldId=record.get(me["idProperty"]);
						me.showEditNodeWin();
					}
				}
			};
		},
		typeMap:{
			"-5":"number",
			"4":"number",
			"1":"string",
			"12":"string",
			"91":"date",
			"92":"time",
			"93":"date",
			"16":"boolean"
		},
		initFieldSet:function(region){
			var me=this,attrs=me["mainMeta"]["attrs"],
			attrMeta=attrs["meta"],
			attrMetaModelId=attrMeta["trait"]["attr"]*1,
			attrMetaModel=refMetaMap[attrMetaModelId],
			attrConfigFields=attrMetaModel["fields"],
			subModelIds=attrMetaModel["children"],
			propattrs=attrMetaModel["attrs"],
			url=contextPath+"meta/singleRecord/"+attrMetaModelId,
			submitUrl=contextPath+"meta/record/"+attrMetaModelId,
			modelName="Ext.ux."+attrMetaModel["code"]+me["globalId"],
			action=propattrs["action"]||{},items=[];
			
			
			Ext.iterate(subModelIds,function(modelId,i){
				var refModel=refMetaMap[modelId],sfields=refModel["fields"],
				fieldset={
						xtype:'fieldset',
						width:'auto',
						layout:'vbox',
						title:refModel["text"],
						defaults:{
							labelAlign:'right'
						}
				};
				fieldset["items"]=FormFieldUtil.getFormFields(modelId,metaData);
				items.push(fieldset);
			});

			items.push({xtype:"numberfield",hidden:true,name:"id"});
			if(!Ext.ClassManager.isCreated(modelName)){
				var fs=FormFieldUtil.getModelFields(attrMetaModelId,metaData,"");
				Ext.define(modelName,{
					extend:"Ext.data.Model",
					fields:fs
				});
			}
			var config=this.attrProps={
					xtype:'form',
					region:region,
					itemId:me["attrCmpId"],
					split:true,
					layout:'form',
					url:submitUrl,
					method:"POST",
					scrollable:true,
					width:400,
					items:items,
					buttons:[{
						text:"提交",
						iconCls:"fa fa-save",
						handler:function(){
							 var form = this.up('form').getForm();
					            if (form.isValid()) {
					                form.submit({
					                    success: function(form, action) {
					                    	Ext.toast("提交成功",'提示', 't');
					                    	
					                    },
					                    failure: function(form, action) {
					                    	Ext.toast(action.result.message,'提示', 't');
					                    }
					                });
					            }
						}
					},{
							text:"刷新",
							iconCls:"fa fa-refresh",
							handler:function(){
								this.up('form').reset();
							}
						}
					]
					
			};
			config["loadData"]=function(id){
				var me=this;
				Ext.Ajax.request({
					url:url,
					method:"GET",
					params:{
						id:id
					},
					success: function(response, opts) {
				         var obj = Ext.decode(response.responseText);
				         if(obj["success"]){
				        	 var data=obj["data"];
				        	 Ext.Object.each(data, function(key, value, myself) {
				        		  if (value=="") {
				        		       data[key]=null;
				        		    }
				        		});
				        	 data["id"]=id;
				        	 var model=Ext.ClassManager.get(modelName);
				        	 var rec=model.create(data);
				        	 me.reset();
				        	 me.loadRecord(rec);
				         }else{
				        	 Ext.toast('数据加载失败','提示');
				         }
				     },

				     failure: function(response, opts) {
				    	 Ext.toast('数据加载失败','提示');
				     }
				});
			};
		}
});

